package com.ctrip.demo.gson;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TemplateMessage {

    public static void main(String[] args) {
        String template = "#{content}加入#{content}失败了，详细信息请到TripPal管理后台查看";
        MessageCommentBO messageCommentBO = new MessageCommentBO();
        messageCommentBO.setContent("xxx");
        messageCommentBO.setCorpId("ctrip");
        String s = fillupValues(messageCommentBO, template);

        System.out.println(s);
    }
    private static String fillupValues(MessageCommentBO contextBO, String template) {
        //get key fields
        List<String> ks = new ArrayList<>();
        String rgex = "#\\{(.*?)\\}";
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(template);
        while (m.find()) {
            ks.add(m.group(1));
        }
        Class<?> clazz = contextBO.getClass();
        for (String fieldStr : ks) {
            try {
                Field field = clazz.getDeclaredField(fieldStr);
                field.setAccessible(true);
                Object val = field.get(contextBO);
                if (val == null) {
                    throw new Exception();
                }
                String res = "";
                if (val instanceof List<?>) {
                    List<String> n = (List<String>) val;
                    res = String.join(",", n);
                } else if (val instanceof String) {
                    res = (String) val;
                }
                template = template.replaceAll("#\\{" + fieldStr + "\\}", res);
            } catch (Exception e) {
//                log.error("build CorpMomentMessage failed.The args is {},{}", contextBO, template, e);
                return null;
            }
        }
        return template;
    }
}
